<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "performance_log".
 *
 * @property int $id ??id
 * @property string $openid openid
 * @property string $category
 * @property int $begin_time
 * @property int $end_time
 * @property string $cost_time
 */
class PfLog extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'performance_log';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['openid'], 'required'],
            [['cost_time'], 'number'],
            [['openid', 'category'], 'string', 'max' => 100],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'openid' => 'Openid',
            'category' => 'Category',
            'begin_time' => 'Begin Time',
            'end_time' => 'End Time',
            'cost_time' => 'Cost Time',
        ];
    }
    
    public function begin($openid, $category)
    {
    	$this->openid = $openid;
    	$this->category = $category;
    	$this->begin_time = microtime(true);
    	
    	if ($this->save()) {
    		return $this->id;
    	}
    	
    	return false;
    }
    
    public function end($category = '')
    {
    	$this->end_time = microtime(true);
		$this->cost_time = (floatval($this->end_time) - floatval($this->begin_time));
		
		if (!empty($category)) {
			$this->category = $category;
		}
		
		$this->save();
    }
}
